<script lang="ts" setup>
import { ref, reactive, onMounted, shallowRef, watch, toRaw, nextTick } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NFormItem,
  NInput,
  NSelect,
  useMessage,
  NScrollbar,
  NSpin,
  NDataTable,
  type SelectOption,
  type DataTableColumns,
  NTimeline,
  NTimelineItem,
  NEllipsis,
  NImageGroup,
  NImage,
  NTooltip
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import basicInfo from '@/components/CollectProcess/BasicInfo.vue'
import InfoBatch from '@/components/CollectProcess/InfoBatch/index.vue'
import useSubmit,{defaultVersionTypeValue,defaultVersionTypeKey} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
const { dfInst, formData:formData1, createVars,submitLoading,submit:submitR } = useSubmit()
const props = defineProps({
  id: { type: String, default: () => null },
  idSelf: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null },
  batchCode: { type: String, default: () => null },
})
const isUpdate = false
const isDetail = true
const tableData1 = ref()
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const array = props?.id?.split(',') || []
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const fileImgList:any = ref([])//附件数组
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null
  }
})
const oneSelectValue = ref<string | null>(null)
const oneSelectOptions = shallowRef<[]>([])
const oneSelectLoading = ref(false)

const twoSelectValue = ref<string | null>(null)
const twoSelectOptions = shallowRef<[]>([])
const twoSelectLoading = ref(false)

const threeSelectValue = ref<string | null>(null)
const threeSelectOptions = shallowRef<[]>([])
const threeSelectLoading = ref(false)

const isUseLastSelect = ref(true)
const clueMethodOptions: any = reactive([])
const formInst = ref<FormInst | null>(null)
const formData = ref({} as any)
// const formData1 = ref({} as any)
const validatorTypeFormItem = () => {
  if (isUseLastSelect.value) return threeSelectValue.value !== null
  return twoSelectValue.value !== null
}
const modelJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
    return res.data
  } catch (error) {
    console.error(error)
  }
}
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeName',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
// const model = shallowRef<any>(baseModel)
// const setModelJson = async (code?: string | null) => {
//   if (!code) return (model.value = toRaw(baseModel))
//   model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
//     if (isArray(obj)) return [...obj, ...src]
//   }) as ModelJson
// }
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    // await setModelJson(res.data.itemTypeCode)
    const { data } = res
    res.data?.fileList?.map((i: any) => {
        fileImgList.value.push({
          name: i.name,
          url: i.path,
          status: 'finished',
          id: i.id
        })
      })
    formData.value = Object.assign(
      {},
      {
        itemName: data.itemName,
        receiveTime: data.receiveTime,
        itemTypeCode: data.itemTypeCode,
        itemTypeName: data.itemTypeName,
        itemNum: data.itemNum,
        collectTypeName: data.collectTypeName,
        receiveUser: data.receiveUser,
        notes: data.notes,
        itemTypeItem: data.itemTypeName
      },
      JSON.parse(data.jsonStr || '{}')
    )
    // fileList.value = data.fileList?.map((e: any, i: number) => ({
    //   id: i,
    //   name: e.name,
    //   status: 'finished',
    //   url: e.path,
    //   remoteId: e.id
    // }))
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
  
}
const otherJson = ref({} as ModelJson)

// const queryTypeJson = async (type: string): Promise<any> => {
//   return await (await fetch(`/form-models/${type}.json`)).json()
// }
// watch(
//   () => formData.value.type,
//   async (type) => {
//     if (!type) return (model.value = baseModel)
//     model.value = mergeWith({}, baseModel, await queryTypeJson(type), (obj: any, src: any) => {
//       if (isArray(obj)) return [...obj, ...src]
//     })
//   },
//   { immediate: true }
// )
const GroupList = ref() //套组
const getInfo = async () => {
  return sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: props.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    keysOf(res.data.detailVo).forEach((e) => {
      form[e] = res.data[e] as never
    })
    console.log(res.data)
    GroupList.value = (res.data?.itemsStagingList ? res.data?.itemsStagingList : []).concat({
      ...res.data?.itemsStaging
    })
    formData1.value = JSON.parse(res.data?.catalogInfo || `{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`)
    if (formData1.value['BMCOM006']) formData1.value['BMCOM006'] = formData1.value['BMCOM006'].split('>').pop()
    // queryJsonBM(res.data?.detailVo?.itemTypeCode)
    checkIsDetail(res.data?.detailVo?.itemCode)
    // modelJson.value = JSON.parse(res.data?.detailVo?.jsonStr)
    // formData1.value = JSON.parse(res.data?.catalogInfo || `{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`)
  })
}
const getFlowFn = () => {
  return sendRequest({
    module: 'collectProcess',
    api: 'orderBaseInfo',
    override: {
      params: {
        id: props?.code
      }
    }
  }).then(async ([err, res]) => {
    if (err) return
    // keysOf(res.data).forEach((e) => {
    //   form[e] = res.data[e] as never
    // })
    tableData1.value = res.data?.workflowInfoVo?.approvalRecordsList || []
  })
}
const timeLineData = ref() //流程数据
const getTimeLine = () => {
  return sendRequest({
    module: 'collectProcess',
    api: 'moveInfoTimeLine',
    uri: {
      subItemCode: props?.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    timeLineData.value = res.data
  })
}
const showLoading = ref(false)

const injectTooltip = () => {
  document.querySelectorAll(`input[class^="n-input"][disabled]`).forEach((e) => {
    // @ts-ignore
    e.parentElement.parentElement.parentElement.setAttribute('data-title', e.value)
    // @ts-ignore
    if (!e.hasAttribute('data-bind') && e.value) {
      e.setAttribute('data-bind', 'true')
      // @ts-ignore
      e.parentElement.parentElement.parentElement.classList.add('tooltip')
    }
  })
}
watch(
  () => route,
  async () => {
    if (route.path == '/collection/process/makeMenu/processDetail' && props.id) {
      showLoading.value = true
      fileImgList.value = []
      await Promise.allSettled([getInfo(), getFlowFn(), getTimeLine()])
      nextTick(() => {
        setTimeout(() => {
          injectTooltip()
        }, 2000)
      })
      showLoading.value = false
    }
  },
  {
    deep: true,
    immediate: true
  }
)

const columns1: DataTableColumns = [
  {
    title: '类型',
    key: 'type',
    width: 50
  },
  {
    title: '人员',
    key: 'userName',
    width: 50
  },
  {
    title: '时间',
    key: 'time',
    width: 100
  },
  {
    title: '结果',
    key: 'result',
    width: 50
  },
  {
    title: '备注',
    key: 'remark',
    width: 150
  }
]

// onMounted(async () => {
//   // 修改回显
//   if (props.id) {
//     getInfo()
//     getTimeLine()
//   }
// })
</script>

<template>
  <DetailFormProvider>
    <div class="main">
      <div class="form_content">
        <NScrollbar>
          <NSpin :show="showLoading">
            <div :class="props?.typeShow == 2 ? 'inlineD' : 'inlineN'">
              <div
                class="content"
                :style="props?.typeShow == 2 ? 'width: 70%' : 'width: 100%'"
              >
            
               
                <div class="topTitle">批次信息</div>
                <InfoBatch :key='props.batchCode' :id="props.batchCode" />
                <div class="dynamic-form-demo">
          <DynamicFormComponent ref="dfInst"  v-if='formData1.BMCOM003' :disabled="true" :data="formData1" :createVars="createVars" />
        </div>
              <div class="detailinlineStyle">
              <span v-show='fileImgList?.length > 0' style='margin-right:10px'>附件:</span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image width="100" height="100" :src="i.url" :key="i.id" v-for="i in fileImgList" />
                  </n-space>
                </n-image-group>
              </div>
            </div>
              <div v-if="props?.typeShow == 1">
                <div class="topTitle">审批信息</div>
                <div class="approve">
                  <div class="box">
                    <span>审批状态</span>
                    <span style="font-size: 20rem">{{ form.workflowInfoVo?.status }}</span>
                  </div>
                  <div class="box">
                    <span>审批流程</span>
                    <div style="color: #5fb17f; font-size: 20rem; font-weight: 500">
                      <div
                        style="display: inline"
                        v-for="(item, index) in form.workflowInfoVo?.workflowList"
                        :key="index"
                      >
                        <span :style="{ textDecoration: item.value ? 'underline' : 'none' }">
                          {{ item.key }}
                        </span>
                        <span v-if="index != form.workflowInfoVo?.workflowList.length - 1">→</span>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="topTitle">审批记录</div>
                <div class="table">
                  <NDataTable
                    :bordered="false"
                    :columns="columns1"
                    :data="tableData1"
                    :pagination="false"
                    striped
                  />
                </div>
              </div>
            </div>
            <div
              class="content1"
              v-if="props?.typeShow == 2"
            >
              <div class="topTitle">生命周期</div>

                <n-timeline style="padding-left: 50rem; padding-top: 50rem">
                  <n-timeline-item
                    v-for="i in timeLineData"
                    type="success"
                    line-type="default"
                  >
                    <span class="namePosition">{{ i.processName }}</span>
                    <div
                      style="height: 20px"
                      v-for="m in i.moveItemList"
                    >
                      {{ m.keyName }}:
                      <NEllipsis style="max-width: 140px">{{ m.valueName }}</NEllipsis>
                    </div>
                  </n-timeline-item>
                </n-timeline>
              </div>
            </div>
          </NSpin>
        </NScrollbar>
      </div>
    </div>
  </DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <!-- <NButton type="primary" style="width: 78px" @click="submit" :loading="loading" v-if="props?.typeShow == 0">
        确定
      </NButton> -->
    </NSpace>
  </FixedAction>
</template>

<style>
.tooltip {
  position: relative;
}
.detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 20px;
}
.tooltip:hover::after {
  display: block;
}

.tooltip:hover::before {
  display: block;
}

.tooltip::after {
  content: attr(data-title);
  position: absolute;
  top: -37rem;
  left: 50%;
  transform: translateX(-50%);
  max-width: 300rem;
  padding: 5rem 10rem;
  background-color: #ffffff;
  color: #333333;
  border-radius: 5rem;
  font-size: 14rem;
  z-index: 999;
  display: none;
}

.tooltip::before {
  content: '';
  position: absolute;
  top: -7rem;
  left: 50%;
  transform: translateX(-50%);
  border: 5rem solid transparent;
  border-top-color: #ffffff;
  display: none;
}
</style>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}
 
.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .dynamic-form-demo {
    background-color: #e1e1e1;
    padding: 30px 45px 10px;
    // height:300px;
  }
  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }

    .content1 {
      width: 400px;
      height: 100%;
      padding: 18rem 33rem 120rem;
      background-color: #ebeceb;
      @include CommonFont;

      :deep(.n-timeline-item-timeline__circle) {
        background-color: #008000;
        border: 1px solid #008000;
      }

      :deep(
          .n-timeline .n-timeline-item .n-timeline-item-content .n-timeline-item-content__content
        ) {
        transform: translate(0, -50%);
        // margin-top: 14px;
        position: relative;
      }

      .namePosition {
        position: absolute;
        left: -96rem;
        top: calc(50% - 11px);
      }
    }
  }

  .approve {
    display: flex;
    width: 100%;
    margin-bottom: 20rem;
    border-bottom: 1px dashed #bc9e70;

    .box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 100rem;
      width: auto;
      height: 90rem;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      padding: 12rem;
      margin-right: 10rem;
      margin-bottom: 20rem;
    }
  }
}

.inlineD {
  display: flex;
  justify-content: space-around;
}

.inlineN {
  display: block;
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
